<template>
<!-- 这是订单详情页面 -->
  <div id="orderD" v-loading="loading">
    <div class="content">
      <div class="orderTitle">
        <h2>{{$t("MyOrder.theOrderDetails")}}</h2>
        <div class="orderText">
          {{$t("orderDetails.orderNumber")}}：{{tableList[0].ordersn}}
          <div class="buttonGroup">
            <!-- <button>联系客服</button> -->
            <button @click="cancelOrder('cancel')" :disabled="disabled" v-if="buttonBool1">{{$t("orderDetails.cancellationOfOrder")}}</button>
            <button @click="evaluate('evaluate')" :disabled="disabled" v-if="buttonBool2">{{$t("MyOrder.evaluate")}}</button>
            <button @click="evaluate('evaluate')" :disabled="disabled" v-if="buttonBool9">{{$t("MyOrder.additionalEvaluation")}}</button>
            <button @click="applyRefund(tableList[0].order_status)" :disabled="disabled" v-if="buttonBool3">{{$t("orderDetails.refund")}}</button>
            <button @click="confirm('receiving')" :disabled="disabled" v-if="buttonBool4">{{$t("MyOrder.confirmReceipt")}}</button>
            <button @click="deleteOrder('delete')" :disabled="disabled" v-if="buttonBool5">{{$t("MyOrder.deleteOrder")}}</button>
            <button @click="payment()" :disabled="disabled" class="payment_button" v-if="buttonBool6">{{$t("MyOrder.payImmediately")}}</button>
            <button @click="viewProgress" v-if="buttonBool7">{{$t("orderDetails.viewProgress")}}</button>
            <button @click="cancel" v-if="buttonBool8">{{$t("orderDetails.withdraw")}}</button>
          </div>
        </div>
      </div>
      <div class="orderStatus">
        <h4>{{tableList[0].order_status | orderStatus(orderStateI18n)}}  {{query.rtype | orderRtype(tableList[0].order_status, query.refund_status, applyStateI18n)}}</h4>
        <h4 class="businessText" v-if="(query.refund_status == -1) && (query.reply !== '' && query.reply !== null)">{{$t("orderDetails.refuse")}}： {{query.reply}}</h4>
        <table class="ul_li_table">
          <tr v-for="(data, index) in goodsList" :key="index">
            <td>
              <div class="detail_Img"><router-link to=""><img :src="url + data.thumb" alt=""></router-link></div>
            </td>
            <td>
              <div class="detail_Text"><router-link to="">{{data.title}}</router-link></div>
            </td>
            <td>
              <div class="danjiaNum"> {{data.price}} 元 × {{data.total}}</div>
            </td>
          </tr>
        </table>
      </div>
      <div class="receivingInformation">
        <h4>{{$t("orderDetails.addressee")}}</h4>
        <table>
          <tr>
            <td>{{$t("orderDetails.name")}}：</td>
            <td>{{tableList[0].realname}}</td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.phone")}}：</td>
            <td>{{tableList[0].mobile | coverUp}}</td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.shippingAddress")}}：</td>
            <td>{{tableList[0].province}} {{tableList[0].city}} {{tableList[0].area}} {{tableList[0].address}}</td>
          </tr>
        </table>
      </div>
      <div class="logistics">
        <h4>{{$t("orderDetails.logisticsInformation")}}</h4>
        <table>
          <tr>
            <td>{{$t("orderDetails.courierCompany")}}：</td>
            <td>{{tableList[0].expresscom}}</td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.courierNumber")}}：</td>
            <td>{{tableList[0].expresssn}}</td>
          </tr>
        </table>
      </div>
      <div class="paymentMethod">
        <h4>{{$t("orderDetails.paymentMethod")}}</h4>
        <p><span>{{$t("orderDetails.paymentMethod")}}：</span> {{tableList[0].paytype | paymentMethod}}</p>
      </div>
      <div class="invoiceInformation">
        <h4>{{$t("orderDetails.invoiceInformation")}}</h4>
        <table>
          <tr>
            <td>{{$t("orderDetails.invoiceType")}}：</td>
            <td><span v-show="invoiceType != null">{{invoiceType}}发票</span></td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.invoiceContent")}}：</td>
            <td><span v-show="invoiceType != null">购买商品明细</span></td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.lookUpType")}}：</td>
            <td>{{invoiceTitle}}</td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.invoiceTitle")}}：</td>
            <td>{{invoiceName}}</td>
          </tr>
          <tr>
            <td>{{$t("orderDetails.identifyNumber")}}：</td>
            <td>{{taxNumber}}</td>
          </tr>
        </table>
      </div>
      <div class="remarks">
        <h4>{{$t("orderDetails.leaveWord")}}：</h4>
        <p>{{tableList[0].remark}}</p>
      </div>
      <div class="orderAmount">
        <div class="floatR">
          <table>
            <tr>
              <td>{{$t("orderDetails.totalPrice")}}：</td>
              <td>{{sum | decimal}} 元</td>
            </tr>
            <tr>
              <td>会员优惠：</td>
              <td>- 0 元</td>
            </tr>
            <tr>
              <td>{{$t("orderDetails.freight")}}：</td>
              <td>0 元</td>
            </tr>
            <tr>
              <td>{{$t("orderDetails.amountPaid")}}：</td>
              <td><span>{{sum | decimal}}</span> 元</td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <!-- 取消订单，弹框，待付款 -->
    <el-dialog
      v-if="(tableList[0].order_status == 0 ? true : false)"
      title=""
      :visible.sync="dialogVisible"
      width="22%"
      @close="closeODetails"
      :before-close="handleClose">
      <el-radio-group v-model="radio" @change="radioChange">
        <el-radio :label="1">不取消了</el-radio>
        <el-radio :label="2">我不想买了</el-radio>
        <el-radio :label="3">信息填写错误，重新拍</el-radio>
        <el-radio :label="4">其它原因</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t("Shopping.no")}}</el-button>
        <el-button type="primary" @click="confirmClosing">{{$t("Shopping.yes")}}</el-button>
      </span>
    </el-dialog>
    <!-- 申请退款，弹框，待发货 -->
    <el-dialog
      v-if="((tableList[0].order_status == 1 || tableList[0].order_status == 2 || tableList[0].order_status == 3) ? true : false)"
      title=""
      :visible.sync="dialogVisible"
      width="25%"
      @close="closeODetails"
      :before-close="handleClose">
      <table class="table_refund">
        <tr>
          <td>{{$t("ASProgress.mode")}}</td>
          <td>
            <div class="selectHandle">
              <select class="choice" v-html="label" @change="huanhuo"></select>
              <i class="el-icon-arrow-down"></i>
            </div>
          </td>
        </tr>
        <tr>
          <!-- 退款原因 -->
          <td>{{moneyText1}}</td>
          <td>
            <div class="selectHandle">
              <select class="choice">
                <option>不想要了</option>
                <option>卖家缺货</option>
                <option>拍错了/订单信息错误</option>
                <option>其它</option>
              </select>
              <i class="el-icon-arrow-down"></i>
            </div>
          </td>
        </tr>
        <tr>
          <!-- 退款说明 -->
          <td>{{moneyText2}}</td>
          <td><input v-model="reasonRefund" type="text" :placeholder="$t('orderDetails.optional')" maxlength=50></td>
        </tr>
        <tr v-show="moneyBool">
          <td>{{$t("ASProgress.money")}}</td>
          <td>￥<el-input-number v-model="refundAmount" :controls="false" :min="0" :max="sum"></el-input-number></td>
        </tr>
        <tr>
          <td>{{$t("orderDetails.upload")}}</td>
          <td>
            <div class="uploadPictures">
              <el-upload
                action="https://api.shop.uekea.com/"
                list-type="picture-card"
                :limit="5"
                ref="upload"
                :file-list="[]"
                :before-upload="beforeUpload"
                :on-success="(response, file, fileList) => {uploadSuccess(fileList)}"
                :on-error="(err, file, fileList) => {uploadError()}" 
                :on-remove="(file, fileList) => {handleRemove()}">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </td>
        </tr>
      </table>
      <p class="tips" v-show="moneyBool">*{{$t("orderDetails.tips")}}￥{{sum}}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t("Shopping.no")}}</el-button>
        <el-button type="primary" @click="confirmClosing">{{$t("Shopping.yes")}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      buttonBool1: false,   // 取消订单
      buttonBool2: false,   // 评价
      buttonBool3: false,   // 申请退款
      buttonBool4: false,   // 确认收货
      buttonBool5: false,   // 删除订单
      buttonBool6: false,   // 立即支付
      buttonBool7: false,   // 查看进度
      buttonBool8: false,   // 取消申请
      buttonBool9: false,   // 追加评价

      loading: true,     // 加载完数据再显示页面
      label: null,    // html标签，申请退款，处理方式下拉框
      tableList: {},    // 订单详情信息
      goodsList: [],      // 商品列表数据
      invoiceName: null,        // 发票人名称，发票抬头
      invoiceTitle: null,   // 抬头类型，个人还是单位
      invoiceType: null,    // 发票材质，纸质
      taxNumber: null,           // 纳税人识别号
      sum: 0,   // 订单总价
      query: {
        id: "",     // 退款id
        order_status: "",   // 订单状态
        reply: "",        // 商家拒绝原因
        rtype: "",        // 处理方式
        refund_status: "",      // 申请状态
      },      // 查询订单申请进度信息
      disabled: false,   // 是否禁用，取消订单，申请退款...
      dialogVisible: false,   // 取消订单弹框
      radio: 1,           // 取消订单原因，单选框，默认下标
      refundOrder: "",    // 新生成的退款订单号，SR
      reasonRefund: "",   // 退款说明，待发货
      refundAmount: "",   // 退款金额，待发货
      endRefund: true,     // 判断售后时间结束后，不显示申请退款按钮
      judge: "",        // 判断是取消订单，还是申请退款，还是申请售后
      uploadImg: [],     // 上传凭证图片数组
      url: "https://mp.uekea.cn/attachment/", //图片拼接
      moneyBool: true,     // 换货的时候隐藏金额，还替换文字
      // moneyText: "退款",        // 退货和换货，文字替换
      moneyText1: this.$t("ASProgress.reason1"),        // 退款原因
      moneyText2: this.$t("ASProgress.explain1"),       // 退货说明，文字替换
      userLevel: null,      // 用户等级，null 普通用户，
    }
  },
  methods: {
    // 各个状态下的按钮的显示
    displayButton() {
      var _this = this;
      let order_status = _this.tableList[0].order_status;
      let refundid = _this.tableList[0].refundid;
      let id = _this.query.id;
      let refund_status = _this.query.refund_status;
      // order_status           查看订单，订单状态，-1交易关闭，0待付款，1待发货，2待收货，3交易完成
      // refundid         查看订单，是否有申请退款，0为没有，有就是退款订单id，申请后取消申请也是有退款id的
      // id               查看进度的退款id，""空为没有，有就是退款id
      // refund_status    查看进度的申请状态， 0 申请 1 完成 3 卖家同意 4 用户填写了快递单号(客户寄回商品) 5 卖家收到退还的货物，再次发货 -1 驳回 -2 客户取消
      // endRefund        true 是在7天内，false 不是在7天内，交易完成的售后时间

      switch (order_status) {
        case -1:
          // 交易关闭
          _this.buttonBool5 = true;   // 删除订单
          // 其它都不显示
          _this.buttonBool1 = false;   // 取消订单
          _this.buttonBool2 = false;   // 评价
          _this.buttonBool3 = false;   // 申请退款
          _this.buttonBool4 = false;   // 确认收货
          _this.buttonBool6 = false;   // 立即支付
          _this.buttonBool7 = false;   // 查看进度
          _this.buttonBool8 = false;   // 取消申请
          _this.buttonBool9 = false;   // 追加评价
          break;
        case 0:
          // 待付款
          _this.buttonBool6 = true;     // 立即支付
          _this.buttonBool1 = true;     // 取消订单
          _this.buttonBool2 = false;    // 评价
          _this.buttonBool3 = false;    // 申请退款
          _this.buttonBool4 = false;    // 确认收货
          _this.buttonBool5 = false;    // 删除订单
          _this.buttonBool7 = false;    // 查看进度
          _this.buttonBool8 = false;    // 取消申请
          _this.buttonBool9 = false;    // 追加评价
          break;
        case 1:
          // 待发货
          _this.buttonBool1 = false;   // 取消订单
          _this.buttonBool2 = false;   // 评价
          _this.buttonBool4 = false;   // 确认收货
          _this.buttonBool5 = false;   // 删除订单
          _this.buttonBool6 = false;   // 立即支付
          _this.buttonBool9 = false;   // 追加评价
          // 申请退款按钮，订单在待发货、待收货、交易完成，并没有申请维权，申请请求为404时，refund_status默认为空，申请状态为取消，驳回时也是为没有申请，并是否为true
          if((refund_status === "" || refund_status === -1 || refund_status === -2 || refund_status === 1) && _this.endRefund) {
            _this.buttonBool3 = true;
          } else {
            _this.buttonBool3 = false;
          }
          // 查看进度和取消申请 按钮，退款id不为空，两个退款id相同，订单不是交易关闭，申请状态为，申请中 或 通过。(有申请，就有查看和取消)
          // 如果 refundid 为空，id也为空，
          if(refundid == id && (refund_status === 0 || refund_status === 3 || refund_status === 4 || refund_status === 5)) {
            _this.buttonBool7 = true;     // 查看进度
            _this.buttonBool8 = true;     // 取消申请
          } else {
            _this.buttonBool7 = false;
            _this.buttonBool8 = false;
          }
          break;
        case 2:
          // 待收货
          _this.buttonBool1 = false;   // 取消订单
          _this.buttonBool2 = false;   // 评价
          _this.buttonBool5 = false;   // 删除订单
          _this.buttonBool6 = false;   // 立即支付
          _this.buttonBool9 = false;   // 追加评价
          // 申请退款按钮，订单在待发货、待收货、交易完成，并没有申请维权，申请请求为404时，refund_status默认为空，申请状态为取消，驳回时也是为没有申请，并是否为true
          if((refund_status === "" || refund_status === -1 || refund_status === -2 || refund_status === 1) && _this.endRefund) {
            _this.buttonBool3 = true;
          } else {
            _this.buttonBool3 = false;
          }
          // 查看进度和取消申请 按钮，退款id不为空，两个退款id相同，订单不是交易关闭，申请状态为，申请中 或 通过。(有申请，就有查看和取消)
          // 如果 refundid 为空，id也为空，
          if(refundid == id && (refund_status === 0 || refund_status === 3 || refund_status === 4 || refund_status === 5)) {
            _this.buttonBool7 = true;     // 查看进度
            _this.buttonBool8 = true;     // 取消申请
          } else {
            _this.buttonBool7 = false;
            _this.buttonBool8 = false;
          }
          // 确认收货按钮，订单在待收货，并没有申请维权，申请请求为404时，refund_status默认为空，申请状态为取消，驳回时也是为没有申请
          if((refund_status === "" || refund_status === -1 || refund_status === -2)) {
            _this.buttonBool4 = true;
          } else {
            _this.buttonBool4 = false;
          }
          break;
        case 3:
          // 交易完成
          _this.buttonBool1 = false;   // 取消订单
          _this.buttonBool4 = false;   // 确认收货
          _this.buttonBool6 = false;   // 立即支付
          // 评价按钮，当评价状态为0，可以评价时，显示评价按钮
          if(_this.tableList[0].iscomment === 0) {
            _this.buttonBool2 = true;
          } else {
            _this.buttonBool2 = false;
          }
          // 追加评价，当评价状态为1，已评价时，显示追加评价按钮，2 是已评价，
          if(_this.tableList[0].iscomment === 1) {
            _this.buttonBool9 = true;
          } else {
            _this.buttonBool9 = false;
          }
          // 申请退款按钮，订单在待发货、待收货、交易完成，并没有申请维权，申请请求为404时，refund_status默认为空，申请状态为取消、驳回、时也是为没有申请，并是否为true
          if((refund_status === "" || refund_status == -1 || refund_status == -2 || refund_status == 1) && _this.endRefund) {
            _this.buttonBool3 = true;
          } else {
            _this.buttonBool3 = false;
          }
          // 查看进度和取消申请 按钮，退款id不为空，两个退款id相同，订单不是交易关闭，申请状态为，申请中 或 通过。(有申请，就有查看和取消)
          // 如果 refundid 为空，id也为空，
          if(refundid == id && (refund_status === 0 || refund_status === 3 || refund_status === 4  || refund_status === 5)) {
            _this.buttonBool7 = true;     // 查看进度
            _this.buttonBool8 = true;     // 取消申请
          } else {
            _this.buttonBool7 = false;
            _this.buttonBool8 = false;
          }
          // 删除订单按钮，订单的申请状态，不是在 申请中 或 通过，就显示删除
          if(refund_status !== 0 || refund_status !== 3 || refund_status !== 4 || refund_status !== 5) {
            _this.buttonBool5 = true;     // 删除订单
          } else {
            _this.buttonBool5 = false;
          }

          break;
        default:
          break;
      }
    },

    // 订单申请售后的结束时间
    endAfterSales() {
      let date = 7 * 24 * 60 * 60;    // 7天的秒数
      if(this.tableList[0].order_status == 3) {
        let tiem = this.tableList[0].ordersn.substr(2, 14);
        let fullYear = tiem.substr(0, 4);  // 年
        let month = tiem.substr(4, 2);  // 月
        let day = tiem.substr(6, 2);  // 日
        let hours = tiem.substr(8, 2);  // 时
        let minutes = tiem.substr(10, 2);  // 分
        let seconds = tiem.substr(12, 2);  // 秒
        let orderDate = new Date(fullYear+"/"+month+"/"+day+" "+hours+":"+minutes+":"+seconds).getTime() / 1000;
        let newDate = Math.floor(new Date().getTime() / 1000);
        if(newDate - (orderDate + date) < 0) {
          this.endRefund = true;
        } else {
          this.endRefund = false;
        }
      }
      
    },
    // 立即支付按钮
    payment() {
      var _this = this;
      let dataChild = JSON.parse(JSON.stringify(_this.tableList[0]));
      let orderObj = {};
      let arr = [];
      let sum = 0;
      // 收货地址数据
      let ShippingAddress = {
        province: dataChild.province,   // 省 
        city: dataChild.city,   // 市
        area: dataChild.area,   // 区 
        address: dataChild.address,   // 详细地址
        isdefault: dataChild.isdefault,  // 是否为默认收货地址
        realname: dataChild.realname,   // 收件人
        mobile: dataChild.mobile,   // 手机号码
        id: dataChild.address_id,   // 收货地址id
        street: "",
        zipcode: ""
      };
      for (let j = 0; j < _this.goodsList.length; j++) {
        sum += Number(_this.goodsList[j].price) * Number(_this.goodsList[j].total);

        let obj = {};   // 商品信息
        obj.goods_id = _this.goodsList[j].goodsid;    // 商品id
        obj.goods_image = _this.goodsList[j].thumb;     // 商品图片
        obj.id = "";                            // 购物车商品id
        obj.merch_id = _this.goodsList[j].merchid;    // 店铺id
        obj.min_price = _this.goodsList[j].price;     // 商品单价
        obj.num = _this.goodsList[j].total;           // 商品购买数量
        obj.title = _this.goodsList[j].title;         // 商品标题
        arr.push(obj);                          // 单个商品的信息添加到商品数组里面
      }

      orderObj.PageID = "OrderDetails";   // 页面id，判断是从购物车进程支付页面的，还是从订单进入支付页面的
      arr.unshift(dataChild.ordersn);   // 订单号
      // 判断发票信息是否为空，不为空就处理，为空就不管
      if(dataChild.invoicename !== "") {
        orderObj.invoiceText = dataChild.invoicename.substring(dataChild.invoicename.indexOf("]")+1, dataChild.invoicename.indexOf("（"));   // 发票人名称
        orderObj.invoiceTitle = dataChild.invoicename.substr(dataChild.invoicename.indexOf("（")+1, 2);   // 发票，个人还是单位
      } else {
        orderObj.invoiceText = "";   // 发票人名称
        orderObj.invoiceTitle = "";          // 发票，个人还是单位
      }
      orderObj.ShippingAddress = ShippingAddress;   // 收货地址
      orderObj.orderCode = dataChild.temporary_ordersn;         // 临时订单号
      orderObj.sum = sum;   // 订单金额
      orderObj.order_status = dataChild.order_status;   // 订单状态
      orderObj.wares = [arr];   // 商品信息

      _this.$store.commit("orderSMS", dataChild.brand_phone);    // 储存当前订单店铺手机号码
      _this.$store.commit("order", orderObj);   // 订单信息存储在vuex
      _this.$router.push({"path": "/payment"});   // 跳转到支付页面
    },
    // 取消订单按钮
    cancelOrder(data) {
      var _this = this;
      _this.judge = data;    // 判断售后弹框
      _this.disabled = true;  // 取消订单,按钮禁用
      _this.dialogVisible = true;   // 打开取消订单原因弹框
    },
    // 取消订单弹框X关闭图标，关闭弹框
    handleClose(done) {
      done();   // x关闭图标，关闭弹框
    },
    // 取消订单，单选框
    radioChange(value) {
      this.radio = value;
    },
    // 订单弹框，关闭回调
    closeODetails() {
      var _this = this;
      _this.dialogVisible = false;   // 关闭取消订单原因弹框
      _this.disabled = true;  // 取消订单,按钮禁用
      _this.reasonRefund = "";    // 申请退款说明，待发货
      setTimeout(function(){
        _this.disabled = false;  // 取消订单，按钮解除禁用
      }, 1000)
      if(_this.uploadImg.length > 0) {
        _this.$refs.upload.clearFiles();    // 清除上传图片
      }
    },
    // 给小于10的时间，前面添加0
    timeFormat(param) {
      // 小于10，数值前面加0，大于10，值就不改变
      return param < 10 ? "0" + param : param;
    },
    // 生成订单号
    ordeRnumber() {
      let time = new Date();
      let orderTime = time.getFullYear() + "" + this.timeFormat(time.getMonth()+1) + this.timeFormat(time.getDate()) + this.timeFormat(time.getHours()) + this.timeFormat(time.getMinutes()) + this.timeFormat(time.getSeconds());
      // 6位随机数
      let ran = "";
      for (let j = 0; j < 6; j++) {
        ran += Math.floor(Math.random() * 10);
      }
      // "SR" + orderTime + (ran);
      this.refundOrder = "SR" + orderTime + (ran);
    },
    // 处理方式，下拉框change事件，选择换货的时候，隐藏金额输入框
    huanhuo() {
      let id = document.getElementsByClassName("choice");
      if(id[0].selectedIndex == 2) {
        this.moneyBool = false;
        this.moneyText1 = this.$t("ASProgress.reason2");
        this.moneyText2 = this.$t("ASProgress.explain2");
      } else {
        this.moneyText1 = this.$t("ASProgress.reason1");
        this.moneyText2 = this.$t("ASProgress.explain1");
        this.moneyBool = true;
      }
      // if(id[0].value == "换货") {
      //   this.moneyBool = false;
      //   this.moneyText = "换货";
      // } else {
      //   this.moneyText = "退款";
      //   this.moneyBool = true;
      // }
    },
    // 申请退款，封装方法
    encapsulationRefund() {
      var _this = this;
      let id = "";
      _this.loading = true;
      _this.ordeRnumber();    // 新生成订单号
      id = document.getElementsByClassName("choice");

      let form = new FormData()
      // 判断上传图片的数组长度，是否大于0
      if(_this.uploadImg.length > 0) {
        for (let i = 0; i < _this.uploadImg.length; i++) {
          form.append("imgs[]", _this.uploadImg[i].raw);        // 上传图片
        }
      } else {
        // 没有上传图片，赋值空
        form.append("imgs[]", "");
      }
      form.append("orderid", _this.tableList[0].orderid);     // 订单id
      form.append("merch_id", _this.goodsList[0].merchid);     // 店铺id
      form.append("refundno", _this.refundOrder);     // 退款订单号,SR
      form.append("rtype", id[0].selectedIndex);     // 处理方式
      form.append("reason", id[1].value);           // 退款原因
      form.append("apply_price", _this.refundAmount);     // 退款金额
      form.append("order_price", _this.sum);            // 订单总价格
      form.append("content", _this.reasonRefund);       // 退款说明
      // 申请退款接口
      _this.$post("user/order/refund", form
      ).then((res)=>{
        if(res.code == 200) {
          _this.query.rtype = id[0].selectedIndex;
          _this.query.refund_status = 0;     // 改变申请状态，0 申请退换货
          _this.loading = false;
          _this.displayButton();    // 显示按钮
        }
      })

    },
    // 订单申请售后弹框，确认按钮
    confirmClosing() {
      var _this = this;
      let reason = "";
      // 商品id，0代表商城本身
      switch (_this.judge) {
        case "cancel":
          // 取消订单，radio（2、3、4是单选框取消订单，1是不取消订单），待付款
          if(_this.radio == 2 || _this.radio == 3 || _this.radio == 4) {
            switch (_this.radio) {
              case 2:
                reason = "我不想买了";
                break;
              case 3:
                reason = "订单信息填写错误，重新拍";
                break;
              case 4:
                reason = "其它原因";
                break;
              default:
                break;
            };
            // 取消订单
            _this.$put("user/order/cancel",{
              openid: _this.$Cookie.getCookie("userID"),
              order_id: JSON.stringify(_this.tableList[0].orderid),
              close_reason: reason,
            }).then((res)=>{
              if(res.code == 204) {
                _this.$router.push({"path": "/accountInformation/myorder"});
              }
            }).catch(()=>{
              _this.radio = 1;     // 取消订单原因，单选框，把默认下标重新赋值为1
            })
            
            _this.disabled = false;     // 解除按钮禁用
          }
          break;
        case "apply1":
          // 申请退款，待发货1
          _this.encapsulationRefund();    // 申请退款
          break;
        case "apply2":
          // 申请退款，待收货2
          _this.encapsulationRefund();    // 申请退款
          break;
        case "apply3":
          // 申请退款，交易完成3
          _this.encapsulationRefund();    // 申请退款
          break;
        // case "receiving":
        //   // 确认收货，待收货
        //   console.log("确认收货，待收货")
        //   break;
        // case "delete":
        //   // 删除订单，完成交易
        //   console.log("删除订单，确认按钮")
        //   break;
        // case "evaluate":
        //   // 评价，完成交易
        //   break;
        default:
          break;
      }
      _this.dialogVisible = false;   // 关闭售后弹框
      
    },
    // 申请退款按钮，待发货，待收货，交易完成
    applyRefund(data) {
      this.dialogVisible = true;    // 打开弹框
      this.judge = "apply" + data;    // 判断申请退款弹框
      if(data == 1) {
        // 退款（仅退款不退货）
        this.label = `<option>退款（仅退款不退货）`;
        // this.label = "<option>"+this.$t("orderDetails.refund2")+"</option>";
      } else if(data == 2) {
        this.label = `<option>退款（仅退款不退货）</option>
                      <option>退款退货</option>
                      <option>换货</option>`;
        // this.label = "<option>"+this.$t("orderDetails.refund2")+"</option><option>"+this.$t("orderDetails.returnGoods")+"</option><option>"+this.$t("orderDetails.exchangeGoods")+"</option>";
      } else if(data == 3) {
        // this.label = "<option>"+this.$t("orderDetails.refund2")+"</option><option>"+this.$t("orderDetails.returnGoods")+"</option><option>"+this.$t("orderDetails.exchangeGoods")+"</option>";
        this.label = `<option>退款（仅退款不退货）</option>
                      <option>退款退货</option>
                      <option>换货</option>`;
      }
      this.huanhuo();               // 下拉框，change事件
    },
    // 删除订单
    deleteOrder() {
      // this.$t("Shopping.Tips")   提示
      var _this = this;
      _this.$confirm(this.$t("orderDetails.confirm1"), this.$t("Shopping.Tips"), {
        confirmButtonText: this.$t("Shopping.yes"),
        cancelButtonText: this.$t("Shopping.no"),
        // type: "warning"
      }).then(() => {
        _this.$dele(`user/order/${_this.$Cookie.getCookie("userID")}/${_this.tableList[0].orderid}`
        ).then((res)=>{
          if(res.code == 204) {
            // 删除订单后，跳转到我的订单
            _this.$MessageAlert(true, this.$t("Shopping.deletesu"), "success");
            _this.$router.push({"path": "/accountInformation/myorder", query: {orderid: _this.tableList[0].orderid}});
          }
        })

        // _this.$MessageAlert(true, "删除成功", "success")
      })
    },
    // 确认收货，待收货
    confirm() {
      var _this = this;
      _this.$confirm(this.$t("orderDetails.confirm2"), this.$t("Shopping.Tips"), {
        confirmButtonText: this.$t("Shopping.yes"),
        cancelButtonText: this.$t("Shopping.no"),
        // type: "warning"
      }).then(() => {
        // 确认收货接口
        _this.$put("user/order/confirm",{
          openid: _this.$Cookie.getCookie("userID"),
          order_id: _this.tableList[0].orderid,
        }).then(res=>{
          if(res.code == 204) {
            _this.$router.push({"path": "/accountInformation/myorder"});
            // _this.tableList[0].order_status = 3;
            // _this.displayButton();      // 显示按钮
          }
        })
      })
    },
    // 查看申请退换货进度，按钮
    viewProgress() {
      this.$router.push({"path": "/accountInformation/ASProgress", query: {orderid: this.tableList[0].orderid}});
    },
    // 取消申请,退换货
    cancel() {
      var _this = this;
      _this.$confirm(this.$t("orderDetails.withdraw2"), this.$t("Shopping.Tips"), {
        confirmButtonText: this.$t("Shopping.yes"),
        cancelButtonText: this.$t("Shopping.no"),
        // type: "warning"
      }).then(() => {
        _this.$put(`refund/cancel/${_this.tableList[0].orderid}`
        ).then((res)=>{
          if(res.code == 201) {
            _this.query.refund_status = -2;     // 改变申请状态，-2 取消申请
            _this.displayButton();    // 显示按钮
            
          } else if(res.code == 400) {
            _this.$MessageAlert(true, this.$t("orderDetails.retry"), "warning");
          }
        })
      })
    },
    // 上传图片前
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;     // 限制上传图片大小10M
      const isJPG = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      let bool = false;
      if(!isLt10M) {
        this.$MessageAlert(true, this.$t("orderDetails.Upload1"), "error");
      }
      if (!isJPG && !isPNG && !isJPEG) {
        this.$MessageAlert(true, this.$t("orderDetails.Upload2"), "error");
        bool = false;
      } else {
        bool = true;
      }
      return bool && isLt10M;
    },
    // 上传成功
    uploadSuccess(fileList) {
      this.uploadImg = fileList;
    },
    // 上传失败
    uploadError() {
      this.$MessageAlert(true, this.$t("orderDetails.fail"), "error");
    },
    // 上传图片，删除上传的图片
    handleRemove() {
      console.log("");
    },
    // 改变订单信息里面的 ‘是否有申请’，状态
    changeStatus(Rstatus) {
      var _this = this;
      // let orderObj = null;
      // 判断申请状态是在5 关闭申请，-1 驳回，-2 取消，就把是否有申请的改为0 否
      if(Rstatus == 5 || Rstatus == -1 || Rstatus == -2) {
        // 循环商品数组，把里面refundid是否有申请，改为 否 0
        // _this.tableList[0].refundid = 0;
      } else if(Rstatus == 0 || Rstatus == 1 || Rstatus == 3 || Rstatus == 4) {     // 申请状态 0 为申请中，1 3 4 为通过申请
        // 循环商品数组，把里面refundid是否有申请，改为 是 从查看订单进度的id中赋值
        _this.tableList[0].refundid = _this.query.id;
      }
      _this.tableList[0].order_status = _this.query.order_status;    // 订单状态
    },
    // 评价和追加评价
    evaluate() {
      this.$router.push({"path": "/accountInformation/orderEvaluation"});     // 跳到评价页面
      this.$store.commit("orderEvaluation", this.tableList);      // 存储到状态管理
    },
    // 支付方式 i18n
    paymentI18n(n) {
      let paytype = "";
      switch (n) {
        case 1:
          paytype = this.$t("MyOrder.remainingSum");
          // paytype = "余额支付";
          break;
        case 2:
          paytype = this.$t("MyOrder.onlinePayment");
          // paytype = "在线支付";
          break;
        case 3:
          paytype = this.$t("MyOrder.payOnDelivery");
          // paytype = "货到付款";
          break;
        case 11:
          paytype = this.$t("MyOrder.backstagePayment");
          // paytype = "后台支付";
          break;
        case 21:
          paytype = this.$t("MyOrder.WeChatPay");
          // paytype = "微信支付";
          break;
        case 22:
          paytype = this.$t("MyOrder.payByAlipay");
          // paytype = "支付宝支付";
          break;
        case 23:
          paytype = this.$t("MyOrder.unionPayPayment");
          // paytype = "银联支付";
          break;
        default:
          break;
      }
      return paytype;
    },
    // 订单状态
    orderStateI18n(order_status) {
      let text = "";
      switch (order_status) {
        case -1:
          text = this.$t("MyOrder.tradingClosed");
          // text = "交易关闭";
          break;
        case 0:
          text = this.$t("MyOrder.WaitForPayment");
          // text = "待付款";
          break;
        case 1:
          text = this.$t("MyOrder.WaitForSending");
          // text = "待发货";
          break;
        case 2:
          text = this.$t("MyOrder.WaitForReceiving");
          // text = "待收货";
          break;
        case 3:
          text = this.$t("MyOrder.transactionCompleted");
          // text = "交易完成";
          break;
        default:
          break;
      }
      return text;
    },
    // 申请状态
    applyStateI18n(rtype, order_status, refund_status) {
      let text = "";
      // 拒绝
      if(refund_status == -1) {
        if(order_status == 2 || order_status == 3) {
          text = "（"+this.$t("orderDetails.applicationStatus1")+"）";
        } else if(order_status == 1) {
          text = "（"+this.$t("orderDetails.applicationStatus2")+"）";
        }
      } else if(refund_status == 0 || refund_status == 3 || refund_status == 4 || refund_status == 5) {
        // 判断处理方式
        switch (rtype) {
          case 0:
            // 退款
            // 判断订单状态，-1交易关闭不显示，0待付款只有取消订单，所以这两个不在考虑范围内
            if(order_status == 2 || order_status == 3) {
              text = "（"+this.$t("orderDetails.applicationStatus3")+"）";
            } else if(order_status == 1) {
              text = "（"+this.$t("orderDetails.applicationStatus4")+"）";
            }
            break;
          case 1:
            // 退货退款
            if(order_status == 2 || order_status == 3) {
              text = "（"+this.$t("orderDetails.applicationStatus5")+"）";
            } else if(order_status == 1) {
              text = "（"+this.$t("orderDetails.applicationStatus6")+"）";
            }
            break;
          case 2:
            // 换货
            if(order_status == 2 || order_status == 3) {
              text = "（"+this.$t("orderDetails.applicationStatus7")+"）";
            } else if(order_status == 1) {
              text = "（"+this.$t("orderDetails.applicationStatus8")+"）";
            }
            break;
          default:
            break;
        }
      }
      return text;
    },
  },
  filters: {
    // 价格，保留两位小数
    decimal(num) {
      return num.toFixed(2);
    },
    // 遮掩手机号码
    coverUp(n) {
      return (n.substring(0, 3) + "****" + n.substr(-4, 4));  // 手机号码，进行遮掩变成*
    },
    // 订单支付方式
    paymentMethod(value) {
      let paytype = "";
      switch (value) {
        case 1:
          paytype = "余额付款";
          break;
        case 2:
          paytype = "在线支付";
          break;
        case 3:
          paytype = "货到付款";
          break;
        case 11:
          paytype = "后台支付";
          break;
        case 21:
          paytype = "微信支付";
          break;
        case 22:
          paytype = "支付宝支付";
          break;
        case 23:
          paytype = "银联支付";
          break;
        default:
          break;
      }
      return paytype;
    },
    // 发票
    // invoice(data, num) {
    //   let text = "";
    //   // switch (num) {
    //   //   case value:
          
    //   //     break;
      
    //   //   default:
    //   //     break;
    //   // }

    //   dataChild[0].invoicename.substring(dataChild[0].invoicename.indexOf("]")+1, dataChild[0].invoicename.indexOf("("));      // 发票人名称
    //   dataChild[0].invoicename.substring(1, dataChild[0].invoicename.indexOf("]"));     // 发票类型，纸质发票
      
    // },
    // 订单状态
    orderStatus(order_status, orderStateI18n) {
      // let text = "";
      // switch (order_status) {
      //   case -1:
      //     text = "交易关闭";
      //     break;
      //   case 0:
      //     text = "待付款";
      //     break;
      //   case 1:
      //     text = "待发货";
      //     break;
      //   case 2:
      //     text = "待收货";
      //     break;
      //   case 3:
      //     text = "交易完成";
      //     break;
      //   default:
      //     break;
      // }
      // return text;
      return orderStateI18n(order_status);
    },
    // 订单申请退款状态，-1为没有
    orderRtype(rtype, order_status, refund_status, applyStateI18n) {
      // refundid，0 没有申请退款，退款id 为有申请。
      // rtype，0 退款，1 退款退货，2 换货
      // order_status, -1交易关闭，0 待付款，1 待发货，2 待收货，3 交易完成，4 退款申请
      // refund_status 申请状态 null 为没有  0 申请 1 完成 3 卖家同意 4 用户填写了快递单号(客户寄回商品) 5 卖家收到退还的货物，再次发货 -1 驳回 -2 客户取消

      // let text = "";
      // // 拒绝
      // if(refund_status == -1) {
      //   if(order_status == 2 || order_status == 3) {
      //     text = "（卖家拒绝售后）";
      //   } else if(order_status == 1) {
      //     text = "（卖家拒绝退款）";
      //   }
      // } else if(refund_status == 0 || refund_status == 3 || refund_status == 4 || refund_status == 5) {
      //   // 判断处理方式
      //   switch (rtype) {
      //     case 0:
      //       // 退款
      //       // 判断订单状态，-1交易关闭不显示，0待付款只有取消订单，所以这两个不在考虑范围内
      //       if(order_status == 2 || order_status == 3) {
      //         text = "（售后退款中）";
      //       } else if(order_status == 1) {
      //         text = "（申请退款中）";
      //       }
      //       break;
      //     case 1:
      //       // 退货退款
      //       if(order_status == 2 || order_status == 3) {
      //         text = "（售后退款退货中）";
      //       } else if(order_status == 1) {
      //         text = "（申请退款退货中）";
      //       }
      //       break;
      //     case 2:
      //       // 换货
      //       if(order_status == 2 || order_status == 3) {
      //         text = "（售后换货中）";
      //       } else if(order_status == 1) {
      //         text = "（申请换货中）";
      //       }
      //       break;
      //     default:
      //       break;
      //   }
      // }
      // return text;
      return applyStateI18n(rtype, order_status, refund_status);
    }
  },
  created () {
    var _this = this;
    let orderid = _this.$route.query.orderid;
    // 查看指定订单详情信息
    _this.$get(`order/info/${_this.$Cookie.getCookie("userID")}/${orderid}`
    ).then(res=>{
      if(res.code == 200) {
        _this.tableList = res.data;      // 全部数据
        // 判断发票信息是否为空，不为空就处理，为空就不管
        if(res.data[0].invoicename !== "") {
          _this.invoiceName = res.data[0].invoicename.substring(res.data[0].invoicename.indexOf("]")+1, res.data[0].invoicename.indexOf("（"));      // 发票人名称
          _this.invoiceType = res.data[0].invoicename.substring(1, res.data[0].invoicename.indexOf("]"));       // 发票材质，发票类型
          _this.invoiceTitle = res.data[0].invoicename.substr(res.data[0].invoicename.indexOf("（")+1, 2);       // 抬头类型，个人还是单位
          // 判断纳税识别号，是否为空
          if(res.data[0].invoicename.indexOf(":") !== -1) {
            _this.taxNumber = res.data[0].invoicename.substring(res.data[0].invoicename.indexOf(":")+1, res.data[0].invoicename.indexOf("）"));
          }
        }
        _this.endAfterSales();      // 判断售后时间是否过期
        let arr = [];
        let sum = 0;
        for (let i = 0; i < res.data.length; i++) {
          let obj = {};
          obj.title = res.data[i].title;              // 商品标题
          obj.thumb = res.data[i].thumb;              // 商品图片
          obj.goodsid = res.data[i].goodsid;          // 商品id
          obj.price = res.data[i].price;              // 商品价格
          obj.total = res.data[i].total;              // 商品数量
          obj.merchid = res.data[i].merchid;          // 店铺id
          arr.push(obj);
          // sum += Number(res.data[i].price);        // 商品金额总价，给的是单个商品总价，直接相加
          sum += (Number(res.data[i].price) * Number(res.data[i].total));        // 商品金额总价，给的是商品单个的价格，要乘数量
        }
        _this.goodsList = arr;            // 商品列表数据
        _this.sum = sum;        // 商品金额总价
        _this.refundAmount = JSON.parse(JSON.stringify(sum));
        
        // 查看订单进度
        _this.$get(`order/refund/${orderid}`
        ).then((res)=>{
          if(res.code == 200) {
            _this.query = res.data;   // 进度信息，赋值
            // _this.changeStatus(res.data.refund_status);   // 调用，改变是否有申请，状态
          } 
          _this.displayButton();    // 显示按钮
          _this.loading = false;     // 加载取消
        })

      }
    })
  }
}
</script>

<style lang="less" scoped>
h4 {
  color: #333;
  text-transform: none;
  margin: 15px 0px;
}
.content {
  padding: 15px;
}
.orderTitle {
  position: relative;
  border-bottom: 1px solid #ddd;
  // padding-bottom: 20px;
  margin-bottom: 20px;
  h2 {
    text-transform: none;
    margin: 30px 0px;
    color: #656565;
  }
  .orderText {
    font-size: 18px;
    height: 80px;
    color: #333;
    .buttonGroup {
      width: 500px;
      float: right;
      text-align: right;
      button {
        background-color: white;
        font-size: 14px;
        color: #888;
        border: 1px solid #ccc;
        padding: 4px 25px;
        margin-left: 15px;
        margin-bottom: 10px;
      }
      .payment_button {
        background-color: rgb(255, 118, 26) !important;
        color: white !important;
      }
      button:hover {
        background-color: #777;
        border-color: #777;
        color: white;
      }
    }
  }
}
.orderStatus {
  border-bottom: 1px solid #ddd;
  padding-bottom: 30px;
  margin-bottom: 30px;
  line-height: 100px;
  color: #333;
  .ul_li_table {
    color: #444;
    // width: 80%;
    max-width: 100%;
    text-align: left;
    tr {
      line-height: 70px;
      .detail_Text {
          margin-left: 30px;
          max-width: 320px;
          display: inline-block;
          vertical-align: middle;
          overflow:hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          a {
            color: #444;
            text-decoration: none;
          }
      }
      // td {
      //   padding: 5px;
      // }
      td:nth-child(2) {
        text-align: left;
        width: 400px;
      }
    }
    .detail_Img {
      height: 64px;
      width: 64px;
      display: inline-block;
      img {
          height: auto;
          width: auto;
      }
    }
  }
  
}

.receivingInformation {
  border-bottom: 1px solid #ddd;
  padding-bottom: 20px;
  margin-bottom: 30px;
  h4 {
    color: #333;
    text-transform: none;
  }
  table {
    tr {
      td {
        height: 30px;
      }
      td:first-child  {
        text-align:justify; 
        text-justify:distribute-all-lines; 
        text-align-last:justify;
      }
      td:last-child  {
        text-indent: 10px;
        color: #656565;
      }
    }
  }
}
.logistics {
  border-bottom: 1px solid #ddd;
  padding-bottom: 20px;
  margin-bottom: 30px;
  table {
    tr {
      td {
        height: 30px;
      }
      td:first-child  {
        text-align:justify; 
        text-justify:distribute-all-lines; 
        text-align-last:justify;
      }
      td:last-child  {
        text-indent: 10px;
        color: #656565;
      }
    }
  }
}
.paymentMethod {
  border-bottom: 1px solid #ddd;
  padding-bottom: 20px;
  margin-bottom: 30px;
  p {
    font-size: 14px;
    color: #656565;
    span {
      color: #333;
      margin-right: 4px;
    }
  }
}
.invoiceInformation {
  border-bottom: 1px solid #ddd;
  padding-bottom: 30px;
  margin-bottom: 30px;
  table {
    tr {
      td {
        height: 30px;
      }
      td:last-child  {
        text-indent: 10px;
        color: #656565;
      }
    }
  }
}
.remarks {
  border-bottom: 1px solid #ddd;
  padding-bottom: 30px;
  margin-bottom: 30px;
  p {
    min-height: 23px;
    font-size: 14px;
    color: #656565;
  }
}
.orderAmount {
  height: 150px;
  .floatR {
    float: right;
    table {
      tr {
        td {
          
          text-align: right;
          height: 30px;
          span {
            font-size: 32px;
          }
        }
        td:last-child  {
          text-indent: 5px;
          color: rgb(255, 118, 26);
        }
      }
      tr:last-child {
        vertical-align: text-bottom;
        td {
          padding-top: 20px;
        }
      }
    }
  }
}
/deep/ .el-dialog {
  min-width: 350px!important;
}

/deep/ .el-radio {
  display: block;
  margin: 10px 0px;
}
.table_refund {
  margin: auto;
  tr {
    height: 40px;
    // line-height: 40px;
    border-bottom: 1px solid #ccc;
    td:first-child {
      width: 132px;
      padding-right: 5px;
      min-width: 100px;
    }
    td:last-child {
      width: 70%;
      input {
        width: calc(100% - 16px);
      }
    }
  }
  tr:nth-child(3) {
    td:last-child {
      input {
        width: 100%;
      }
    }
  }
  tr:last-child {
    line-height: 0px;
  }
}
.tips {
  width: 400px;
  margin: auto;
  margin-top: 5px;
  font-size: 13px;
  color: red;
}
.selectHandle {
  position: relative;
  width: 100%;
  .choice {
    width: 100%;
    height: 35px;
  }
  .el-icon-arrow-down {
    position: absolute;
    top: 0px;
    right: 0px;
    display: inline-block;
    height: 36px;
    line-height: 36px;
    width: 12%;
    text-align: center;
    background-color: white;
  }
}

// 上传凭证
.uploadPictures {
  padding: 10px 0px;
}
/deep/ .el-upload__input {
  display: none;
}
/deep/ .el-upload--picture-card {
  width: 80px;
  height:80px;
  line-height:80px;
  border-radius: 0px;
}
/deep/ .el-upload-list__item {
  width: 80px !important;
  height: 80px !important;
  // line-height:80px !important;
  border-radius: 0px !important;
  // margin: 0px 8px 0px 0px !important;
}

// .avatar-uploader-icon {
//   font-size: 28px;
//   color: #8c939d;
//   width: 100px;
//   height: 100px;
//   line-height: 100px;
//   text-align: center;
//   border: 1px dashed #ccc;
// }
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
/deep/ .el-input-number {
  width: calc(100% - 16px);
}
/deep/ .el-input__inner {
  border: none;
  text-align: left !important;
  padding: 0px 5px !important;
}


// 测试按钮
.cheshi {
  button {
    margin-right: 10px;
    padding: 3px 20px;
    border: 1px solid red;
  }
}
.businessText {
  font-size: 16px;
  margin: 0px;
  margin-bottom: 15px;
  padding: 7px 0px;
  background-color: rgba(255, 177, 60, 0.7);
}
</style>

